package com.tarena.lbs.filter;

import com.tarena.lbs.config.BlacklistConfig;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class BlacklistFilter extends AbstractGatewayFilterFactory<BlacklistFilter.Config> {

    private final Set<String> blacklistUserIds;

    // 注入黑名单配置
    public BlacklistFilter(BlacklistConfig blacklistConfig) {
        super(Config.class);
        this.blacklistUserIds = blacklistConfig.blacklistUserIds();
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 假设从请求头里获取用户 ID，实际可根据业务改（比如 Token 解析、参数等）
            String userId = exchange.getRequest().getHeaders().getFirst("userId");
            if (userId != null && blacklistUserIds.contains(userId)) {
                // 命中黑名单，返回 403 禁止访问
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
            // 未命中，继续执行后续过滤器、路由到微服务
            return chain.filter(exchange);
        };
    }

    // 空配置类，若需可扩展参数可在这里定义
    public static class Config {
    }
}